package pw.h57.cimple.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import pw.h57.cimple.entity.Article;
import pw.h57.cimple.entity.Cate;
import pw.h57.cimple.interceptor.IndexInterceptor;
import pw.h57.cimple.util.StringUtils;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
/**
 * 首页页面跳转
 * @author crazy_000
 *
 */
@Before(IndexInterceptor.class)
public class IndexController extends Controller {
	public void index(){
		int pageNum = getParaToInt(0, 1);
		setAttr("title", "首页");
		Page<Article> pageArt = Article.getArticleByPageIndex(pageNum);
		for(int i = 0; i < pageArt.getList().size(); i++) {
			Article art = pageArt.getList().get(i);
			art.set("content", StringUtils.cleanHtmlTags(art.getStr("content")));
		}
		setAttr("pageArt", pageArt);
	}
	
	public void tag(){
		String tag = getPara(0, "");
		int pageNum = getParaToInt(1, 1);
		try {
			tag = URLDecoder.decode(tag,"utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		tag = tag.trim();
		System.out.println(tag + "-------------------");
		setAttr("tag", tag);
		Page<Article> pageArt = Article.getArticleByTag(tag,pageNum);
		for(int i = 0; i < pageArt.getList().size(); i++) {
			Article art = pageArt.getList().get(i);
			art.set("content", StringUtils.cleanHtmlTags(art.getStr("content")));
		}
		setAttr("title", tag);
		setAttr("pageArt", pageArt);
	}
	
	public void cate(){
		String cate = getPara(0, "");
		int pageNum = getParaToInt(1, 1);
		try {
			cate = URLDecoder.decode(cate,"utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		cate = cate.trim();
		System.out.println(cate + "-------------------");
		setAttr("cate", cate);
		Page<Article> pageArt = Article.getArticleByCateId(Cate.getCateIdByAlias(cate), pageNum);
		for(int i = 0; i < pageArt.getList().size(); i++) {
			Article art = pageArt.getList().get(i);
			art.set("content", StringUtils.cleanHtmlTags(art.getStr("content")));
		}
		setAttr("title", Cate.getCateNameByAlias(cate));
		setAttr("pageArt", pageArt);
	}
	
	public void article(){
		String transTitle = getPara();
		
		Article art = Article.getArticleByTransTitle(transTitle);
		if(art == null) {
			art = Article.getArticleById(transTitle);
		}
		setAttr("title", art.getStr("title"));
		setAttr("art", art);
		
	}
}
